import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'

export const useRatingStore = defineStore('rating', () => {
    // 状态
    const ratings = ref<any[]>([])
    const loading = ref(false)

    // 计算属性
    const userRatings = computed(() => {
        return ratings.value.filter(rating => rating.userId === useUserStore().userInfo.id)
    })

    const receivedRatings = computed(() => {
        return ratings.value.filter(rating => rating.targetId === useUserStore().userInfo.id)
    })

    const averageRating = computed(() => {
        const userRatings = receivedRatings.value
        if (userRatings.length === 0) return 0
        return userRatings.reduce((sum, rating) => sum + rating.score, 0) / userRatings.length
    })

    // 方法
    const fetchRatings = async (params = {}) => {
        try {
            loading.value = true
            // TODO: 实现获取评价列表的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            // 模拟数据
            ratings.value = Array(20).fill(null).map((_, index) => ({
                id: index + 1,
                orderId: index + 1,
                userId: Math.random() > 0.5 ? useUserStore().userInfo.id : index + 100,
                targetId: Math.random() > 0.5 ? useUserStore().userInfo.id : index + 200,
                type: Math.random() > 0.5 ? 'buyer' : 'seller',
                score: Math.floor(Math.random() * 2) + 4, // 4-5分
                content: `这是第 ${index + 1} 条评价内容...`,
                images: Array(Math.floor(Math.random() * 3)).fill(null).map((_, i) =>
                    `https://via.placeholder.com/200/409EFF/FFFFFF?text=Rating+${index + 1}+Image+${i + 1}`
                ),
                createdAt: new Date(Date.now() - Math.random() * 86400000 * 30).toISOString()
            }))
        } catch (error) {
            console.error('获取评价列表失败:', error)
        } finally {
            loading.value = false
        }
    }

    const submitRating = async (data: any) => {
        try {
            loading.value = true
            // TODO: 实现提交评价的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            const rating = {
                id: ratings.value.length + 1,
                userId: useUserStore().userInfo.id,
                ...data,
                createdAt: new Date().toISOString()
            }

            ratings.value.unshift(rating)
            return rating
        } catch (error) {
            console.error('提交评价失败:', error)
            return null
        } finally {
            loading.value = false
        }
    }

    const updateRating = async (ratingId: number, data: any) => {
        try {
            loading.value = true
            // TODO: 实现更新评价的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            const rating = ratings.value.find(r => r.id === ratingId)
            if (rating) {
                Object.assign(rating, data)
            }
            return true
        } catch (error) {
            console.error('更新评价失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    const deleteRating = async (ratingId: number) => {
        try {
            loading.value = true
            // TODO: 实现删除评价的API调用
            await new Promise(resolve => setTimeout(resolve, 1000))

            const index = ratings.value.findIndex(r => r.id === ratingId)
            if (index > -1) {
                ratings.value.splice(index, 1)
            }
            return true
        } catch (error) {
            console.error('删除评价失败:', error)
            return false
        } finally {
            loading.value = false
        }
    }

    const getRatingStats = computed(() => {
        const stats = {
            total: receivedRatings.value.length,
            average: averageRating.value,
            distribution: {
                5: 0,
                4: 0,
                3: 0,
                2: 0,
                1: 0
            }
        }

        receivedRatings.value.forEach(rating => {
            stats.distribution[Math.floor(rating.score)]++
        })

        return stats
    })

    return {
        // 状态
        ratings,
        loading,

        // 计算属性
        userRatings,
        receivedRatings,
        averageRating,
        getRatingStats,

        // 方法
        fetchRatings,
        submitRating,
        updateRating,
        deleteRating
    }
}) 